package com.link.serve.tcp;

import com.link.serve.constants.LinkRedisKey;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.CommandLineRunner;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

import javax.annotation.PreDestroy;
import java.util.List;

@Slf4j
@Component
@AllArgsConstructor//项目启动类运行后携带启动CommandLineRunner
public class IMServerGroup implements CommandLineRunner {

    public static volatile long serverId = 0;
    RedisTemplate<String, Object> redisTemplate;
    //对于容器中被注入的实现了LinkServer的子类会被springboot识别注册并组装为服务list
    private final List<LinkServer> imServers;

    public boolean isReady() {//判断服务器是否就绪
        for (LinkServer imServer : imServers)
            if (!imServer.isReady())
                return false;
        return true;
    }
    @Override
    public void run(String... args) throws Exception {
        // 初始化SERVER_ID
        String key = LinkRedisKey.LINK_MAX_SERVER_ID;
        serverId = redisTemplate.opsForValue().increment(key, 1);
            for (LinkServer imServer : imServers) imServer.start();// 根据那些被注册的启动服务子类来依次启动
    }

    @PreDestroy
    public void destroy() {// 停止服务
        for (LinkServer imServer : imServers) imServer.stop();
    }
}
